import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Form, Checkbox,Input, DatePicker, Table, Button, Card, Avatar, Radio, Modal,Icon,InputNumber,Row,Col,message,Upload,Pagination
} from 'antd';
import styles from './style.less';
import moment from 'moment';
import WriterList from '../../components/WriterOff/list/WriterList';
import WriterAddedList from '../../components/WriterOff/list/WriterAddedList';
import UploadFile from '../../components/Upload/index';
import docCookies from "../../common/DocCookies";
const FormItem = Form.Item;
const { TextArea } = Input;
const plainOptions = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
@connect(state => ({
  coupon: state.coupon,
}))
@Form.create()
export default class CouponAdd extends PureComponent {
  state = {
    pageNo:1,
    pageSize:5,
    total:0,
    addedPageNo:1,
    addedPageSize:5,
    addedTotal:0,
    previewVisible: false,
    previewImage: '',
    fileList: [],
    checkUserListData: [],
    checkUserAddedListData: [],
    rpcStarttime: '',
    rpcEndtime: '',
    rpcUsetime: [],
    maxCount: 1,
    modalVisible:false,
    tableVisible:false,
    rpcLogo:'',
    rsId:docCookies.getItem("rsId"),
    userId:docCookies.getItem("userId"),
    id:-1,
    defaultList:[],
    isEdit:false,
    formLoading: false,
    showDetail:false,
    visible:false,
    indeterminate: true,
    checkAll: false,
  };

  ////初始化渲染后触发 整个过程只调用一次
  componentDidMount() {
    const { form , dispatch} = this.props;
    const { checkUserAddedListData } = this.state;

    if(this.props.location.query) {
      var pcId = this.props.location.query.pcId;
      var showDetail = this.props.location.query.showDetail;
      if (pcId) {
        const params = {
          pcId: pcId
        };
        this.setState({
          showDetail:showDetail
        });
        dispatch({
          type: 'coupon/fetchGetPluginCouponById',  //请求的action
          payload: params,
          callback: (res) => {
            form.setFields({
              rpcName: {value: res.rpcName},
              rpcTitle: {value: res.rpcTitle},
              rpcMaxCount: {value: res.rpcMaxCount},
              rpcCouLimit: {value: res.rpcCouLimit},
              rpcUseDescription: {value: res.rpcUseDescription},
              rpcUseNotes: {value: res.rpcUseNotes},
              rpcExpire: {value: [moment(res.starttime), moment(res.endtime)]},
              rpcUsetime: {value: res.rpcUsetime.split(",")},
            })
            this.state.rpcUsetime = res.rpcUsetime.split(",")
            var addedListData = [];
            if(res.checkUserAddedListData != ""){
              addedListData = JSON.parse(res.checkUserAddedListData);
            }

            for (var i = 0; i < addedListData.length; i++) {
              var pd = {
                id: addedListData[i].id,
                nickName: addedListData[i].name,
                phone: addedListData[i].phone,
              }
              checkUserAddedListData.push(pd)
            }
            this.setState({
              checkUserAddedListData: checkUserAddedListData.concat([]),
              addedTotal: checkUserAddedListData.length,
              rpcLogo:res.rpcLogo==""?"":res.rpcLogo,
              rpcStarttime:res.starttime,
              rpcEndtime:res.endtime,
              rsId:res.rsId,
              id:pcId,
              isEdit:true,
              defaultList:[{
                uid: -1,
                name: '1.png',
                status: 'done',
                url:res.rpcLogo==""?require("../../../public/default_avatar.png"):res.rpcLogo,
              }]
            });
          }
        });
      }
    }
  }




  addWriter = (record) => {
    const { checkUserAddedListData } = this.state;

    var _isExit = false;
    for(var i = 0;i<checkUserAddedListData.length;i++){
      if(record == checkUserAddedListData[i]){
        _isExit = true;
        break;
      }
    }

    if(!_isExit){
      checkUserAddedListData.push(record)
      this.setState({
        checkUserAddedListData:checkUserAddedListData.concat([]),
        addedTotal:checkUserAddedListData.length
      });
      message.success('添加成功');
    }else{
      message.success('此核销员已被添加');
    }
  }

  delAddedWriter = (index) => {
    const { checkUserAddedListData } = this.state;

    checkUserAddedListData.splice(index,1)
    this.setState({
      checkUserAddedListData:checkUserAddedListData.concat([]),
      addedTotal:checkUserAddedListData.length
    });
  }

  CloseWriterModal = () => {
    this.setState({
      modalVisible: false,
    });
  }

  /**
   * 打开核销员选择窗口：唐腾飞注释掉内部方法，初始化不需要显示核销员
   * @param flag
   */
  openWriterDialog = (flag) => {
    this.setState({
      modalVisible: !!flag,
     /* loadMethod: this.loadMethod(this.state.pageNo,this.state.pageSize)*/
    });
  }

  /**
   * 加载核销员方法
   * @param pageNo
   * @param pageSize
   */
  loadMethod(pageNo,pageSize,nameOrPhone){
    var self  = this;
    const { dispatch } = self.props;
    const params = {
      pageNo: pageNo,
      pageSize: pageSize,
      searchValue:nameOrPhone
    };
    dispatch({
      type: 'coupon/fetchCheckUserList',  //请求的action
      payload:params,
      callback:(res) =>{
        self.setState({
          checkUserListData: res.list,
          total:res.total
        });
      }
    });
  }

  /**
   * 分页查询显示核销员方法
   * @param page
   * @param pageSize
   */
  writeListChange = (page, pageSize,nameOrPhone) => {
    var self  = this;
    self.setState({
      pageNo:page,
      pageSize:pageSize
    },() => {
      self.loadMethod(page,pageSize,nameOrPhone)
    });
  }

  handleSubmit = () => {
    const { form ,dispatch} = this.props;
    const { checkUserAddedListData } = this.state;
    this.setState({
      formLoading: true
    })
    form.validateFields(
      (err, values) => {
        if (!err) {
          if(this.state.rpcLogo == "") {
            message.warn("请上传头像");
            this.setState({
              formLoading: false
            })
            return;
          }
          if(values.rpcCouLimit == "" || values.rpcCouLimit == undefined){
            values.rpcCouLimit = 1;
          }
          if(this.state.addedTotal == 0 ) {
            this.setState({
              formLoading: false
            })
            message.warn("请添加核销员");
            return;
          }
          if(this.state.rpcUsetime.length == 0 ) {
            this.setState({
              formLoading: false
            })
            message.warn("请勾选可用时段");
            return;
          }
          values.rpcStarttime = this.state.rpcEndtime;
          values.rpcEndtime = this.state.rpcEndtime;
          delete values.rpcExpire;
          values.rpcUsetime = this.state.rpcUsetime.join(",");
          var writerList = [];
          for(var i = 0;i<checkUserAddedListData.length;i++){
            writerList.push({
              id:checkUserAddedListData[i]['id'],
              phone:checkUserAddedListData[i]['phone'],
              name:checkUserAddedListData[i]['nickName'],
            })
          }
          values.rpcWriteOff = JSON.stringify(writerList);
          values.rpcLogo = this.state.rpcLogo;
          values.rsId = this.state.rsId;
          if(this.state.id != -1) values.id = this.state.id;
          dispatch({
            type: 'coupon/fetchSaveOrUpdateCoupon',  //请求的action
            payload:values,
            callback:(res) =>{
              message.success(res.msg);
              setTimeout(this.cancelBack(),200);
            }
          });
        } else {
          this.setState({
            formLoading: false
          })
        }
      }
    );
  }

  getImageSrc = (imgSrc) => {
    this.setState({
      rpcLogo: imgSrc[0]
    })
  }

  onDataPickChange = (dates, dateStrings) => {
    this.setState({
      rpcStarttime: dateStrings[0],
      rpcEndtime: dateStrings[1]
    })
  }

  usetimeOnChange = (checkedValue) => {
    this.setState({
      rpcUsetime: checkedValue
    })
  }

  maxCountOnChange = (checkedValue) => {
    this.setState({
      maxCount: checkedValue
    })
  }

  cancelBack = () => {
    history.go(-1);
  }

  onCheckAllChange = (e) => {
    this.setState({
      rpcUsetime: e.target.checked ? plainOptions : [],
      indeterminate: false,
      checkAll: e.target.checked,
    });
  }

render() {
    const { getFieldDecorator  } = this.props.form;
    const { modalVisible,total,pageNo,pageSize,checkUserListData,addedPageNo,addedPageSize,
      addedTotal,checkUserAddedListData ,defaultList,userId,formLoading,showDetail,rpcLogo} = this.state;
    const CheckboxGroup = Checkbox.Group;
    const RangePicker = DatePicker.RangePicker;

    const plainOptions = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 10, offset: 7},
      },
    };

    return (

      <div>
        <Form
          //onSubmit={this.handleSubmit}
          hideRequiredMark
          style={{ marginTop: 8 }}
        >
          <Card title="基本信息">
            <FormItem {...formItemLayout} label="商家logo">
              {showDetail?
                <img alt="example"  src={rpcLogo} style={{ width: 86, height: 86 }}/>
                :
                <UploadFile
                  maxFileCount = {1}
                  defaultList={defaultList}
                  getImgSrc={(imgSrc)=> this.getImageSrc(imgSrc)}
                  buttonName = '头像上传'
                  acceptName = 'image/*'
                  suffixDefault = {['jpg','png','jpeg']}
                  data={{
                    userId:userId
                  }}
                />
              }
            </FormItem>
            <FormItem {...formItemLayout} label="商户名称">
              {getFieldDecorator('rpcName', {
                rules: [{
                  required: true,
                  message: '请输入商户名称',
                }]
              })(
                <Input placeholder="商户名称" disabled={showDetail}/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="优惠券标题">
              {getFieldDecorator('rpcTitle', {
                rules: [{
                  required: true,
                  message: '请输入优惠券标题',
                }]
              })(
                <Input placeholder="优惠券标题" disabled={showDetail}/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="优惠券有效期">
              {getFieldDecorator('rpcExpire', {
                rules: [{
                  required: true,
                  message: '请选择有效期',
                }],
              })(
                <RangePicker
                  ranges={{ "今天": [moment(), moment()], '这个月': [moment(), moment().endOf('month')] }}
                  showTime
                  format="YYYY/MM/DD HH:mm:ss"
                  onChange={this.onDataPickChange}
                  style={{ width: '100%' }}
                  disabled={showDetail}
                />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="可用时段">
              {getFieldDecorator('rpcUsetime')(
                <div>
                  {showDetail ? null
                  :
                <Checkbox
                  indeterminate={this.state.indeterminate}
                  onChange={this.onCheckAllChange}
                  checked={this.state.checkAll}
                >
                  全选
                </Checkbox>}
                <CheckboxGroup options={plainOptions} value={this.state.rpcUsetime} style={{ paddingTpo: 100 }} onChange={this.usetimeOnChange}  disabled={showDetail}>
                </CheckboxGroup>
                </div>
              )}
            </FormItem>
          </Card>
          <FormItem {...formItemLayout}  >
          </FormItem>
          <Card title="优惠信息">
            <FormItem {...formItemLayout} label="优惠券总量">
              {getFieldDecorator('rpcMaxCount', {
                rules: [{
                  required: true,
                  message: '优惠券总量',
                }],
                initialValue:1
              })(
                <InputNumber min={1}  style={{ width: '100%' }} onChange={this.maxCountOnChange}  disabled={showDetail}/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="领券限制" help="每个用户领券上限，如不填则默认为1">
              {getFieldDecorator('rpcCouLimit', {
                rules: [{
                  required: false,
                  message: '领券限制',
                }],
                initialValue:1
              })(
                <InputNumber min={1} max={this.state.maxCount} style={{ width: '100%' }}  disabled={showDetail}/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="优惠说明">
              {getFieldDecorator('rpcUseDescription', {
                rules: [{
                  required: true,
                  message: '请输入优惠说明',
                }]
              })(
                <TextArea placeholder="优惠说明" autosize={{ minRows: 2, maxRows: 8 }}  disabled={showDetail}/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="使用须知">
              {getFieldDecorator('rpcUseNotes', {
                rules: [{
                  required: true,
                  message: '请输入使用须知',
                }]
              })(
                <TextArea placeholder="使用须知" autosize={{ minRows: 2, maxRows: 8 }}  disabled={showDetail}/>
              )}
            </FormItem>
          </Card>
          <FormItem {...formItemLayout}  >
          </FormItem>
          <Card title="核销员">
            <Row gutter={16} style={{ marginBottom: '10px' }}>
              <Col className="gutter-row" span={4}>
              </Col>
              <Col className="gutter-row" span={10}>
                <span>只有核销员可对本次优惠活动的优惠券进行扫码核销、查看领取记录、使用记录</span>
              </Col>
              <Col className="gutter-row" span={6}>
                {showDetail?"":<Button type="primary" icon="plus" style={{ float:'right' }}
                                       onClick={() => this.openWriterDialog(true)}>添加</Button>}
              </Col>
              <Col className="gutter-row" span={4}>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col className="gutter-row" span={4}>
              </Col>
              <Col className="gutter-row" span={16}>
                <WriterAddedList
                  checkUserListData={checkUserAddedListData}
                  delAddedWriter={this.delAddedWriter}
                  showDelBtn = {showDetail}
                  total = {addedTotal}
                  pageNo = {addedPageNo}
                  pageSize = {addedPageSize}
                />
              </Col>
              <Col className="gutter-row" span={4}>
              </Col>
            </Row>
          </Card>
          <FormItem {...submitFormLayout} style={{ marginTop: 20 }}>
            <Row gutter={16} style={{ marginBottom: '10px' }}>
              <Col className="gutter-row" span={9}>
              </Col>
              <Col className="gutter-row" span={3}>
                {showDetail?null:
                <Button type="primary" htmlType="submit" loading={formLoading}
                        onClick={() => this.handleSubmit()}>保存</Button>}
              </Col>
              <Col className="gutter-row" span={3}>
                <Button onClick={() => this.cancelBack()}>{showDetail?"返回":"取消"}</Button>
              </Col>
              <Col className="gutter-row" span={9}>
              </Col>
            </Row>
          </FormItem>
        </Form>
        <Modal
          title="新增核销员"
          visible={modalVisible}
          onOk={this.CloseWriterModal}
          onCancel={() => this.openWriterDialog()}
        >
          <WriterList
            checkUserListData={checkUserListData}
            onChange={(page,pageSize,nameOrPhone) => this.writeListChange(page, pageSize,nameOrPhone)}
            total = {total}
            pageNo = {pageNo}
            pageSize = {pageSize}
            addWriter = {this.addWriter}
          />
        </Modal>
      </div>
    );
  }
}
